<template>
    <div class="reg">
        <h3>注册</h3>
        <el-divider></el-divider>
        <el-input v-model="username" placeholder="请输入" class="mb">
            <template slot="prepend">用户</template>
        </el-input>
        <el-input type="password" v-model="password" placeholder="请输入" class="mb">
            <template slot="prepend">密码</template>
        </el-input>
        <span class="errinfo">{{message}}</span>
        <el-button type="primary" @click="reg">注册</el-button>
        <el-button @click="$router.push('/login')">登录</el-button>
    </div>
</template>
<script>
export default {
    data:()=>({
        username:'',
        password:'',
        message:''
    }),
    beforeRouteLeave(to,from,next){
        if(!this.message){
            if(this.username||this.password){
                let al = window.confirm("是否要离开？");
                next(al);
            }else{
                next();
            }
        }
    },
    methods:{
       async reg(){
        let formdata=new FormData();
        formdata.append('username',this.username);
        formdata.append('password',this.password);
        let res = await this.$axios({
                url:'/api/reg',
                method:'post',
                data:formdata
            })
            // .then(r=>{
            //     console.log("res.data*************"+r);
            // })
            ;
            console.log("**res****reg***"+JSON.stringify(res.data));
            if(res.data.code!='0'){
                this.message=res.data.msg;
            }else{
               this.$router.push('/login'); 
            }
        }
    }
}
</script>
<style scoped>
/* 使用scoped 声明为当前组件私有化使用 */
.reg {
    width:35%;
    height: auto;
    position: absolute;
    left: 50%;
    top:50%;
    margin-left: -17%;
    transform: translateY(-50%);
}.mb{
    margin-bottom: 20px;
}
.errinfo{
    color: red;
}
</style>